package com.zk.fm.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnKeyListener;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.zk.fm.R;
import com.zk.fm.entity.User;
import com.zk.fm.util.AppInfo;
import com.zk.fm.util.WebServiceUtil;

public class LoginActivity extends Activity {
	private Button login;
	private Button register;
	private Button visitor;
	private ProgressDialog pd;
	private EditText account;
	private EditText password;
	private long id;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		initView();
		setListener();
	}

	@Override
	protected void onResume() {
		super.onResume();
		loadSavedAccount();
	}

	private void loadSavedAccount() {
		SharedPreferences preferences = getSharedPreferences(
				AppInfo.xmlSavedName, PreferenceActivity.MODE_PRIVATE);
		String savedAccount = preferences.getString("account", "");
		String savedPassword = preferences.getString("password", "");
		account.setText(savedAccount);
		password.setText(savedPassword);
	}

	private void initView() {
		account = (EditText) findViewById(R.id.account);
		password = (EditText) findViewById(R.id.password);
		login = (Button) findViewById(R.id.login);
		register = (Button) findViewById(R.id.register);
		visitor = (Button) findViewById(R.id.visitor);
		pd = new ProgressDialog(this);
		pd.setMessage(getString(R.string.Login_in));
		pd.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					id = -1;
				}
				return false;
			}
		});
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (id != msg.arg1) {
				return;
			}

			pd.dismiss();
			if (msg.what == 1) {
				saveToPref();
				AppInfo.currentAccount = account.getText().toString().trim();
				jumpToMainPage();
			} else {
				Toast.makeText(LoginActivity.this, R.string.loginFail,
						Toast.LENGTH_SHORT).show();
			}
		};
	};

	private void setListener() {
		login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				boolean validateResult = clientValidate();
				if (!validateResult) {
					return;
				}
				pd.show();
				Thread loginThread = new Thread() {
					public void run() {
						id = this.getId();
						List<Object> l = new ArrayList<Object>();
						User u = new User();
						u.setAccount(account.getText().toString().trim());
						u.setPassword(password.getText().toString().trim());
						l.add(u);
						boolean loginResult;
						try {
							loginResult = Boolean.parseBoolean(WebServiceUtil
									.callWebService(
											WebServiceUtil.METHOD_LOGIN, l,
											10000));
							System.out.println("loginResult =" + loginResult);
							if (loginResult) {
								mHandler.sendMessage(mHandler.obtainMessage(1,
										(int) getId(), 0));
							} else {
								mHandler.sendMessage(mHandler.obtainMessage(0,
										(int) getId(), 0));
							}
						} catch (Exception e) {
							e.printStackTrace();
							mHandler.sendMessage(mHandler.obtainMessage(0, (int)id, 0));
						}
					};
				};
				loginThread.start();

			}
		});
		visitor.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				AppInfo.currentAccount = "";
				jumpToMainPage();
			}
		});
		register.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent i = new Intent();
				i.setClass(LoginActivity.this, RegisterActivity.class);
				startActivity(i);
			}
		});

	}

	protected void saveToPref() {
		SharedPreferences preferences = getSharedPreferences(
				AppInfo.xmlSavedName, PreferenceActivity.MODE_PRIVATE);
		Editor edit = preferences.edit();
		edit.putString("account", account.getText().toString().trim());
		edit.putString("password", password.getText().toString().trim());
		edit.commit();
	}

	protected void jumpToMainPage() {

		Intent i = new Intent();
		i.setClass(LoginActivity.this, MainActivity.class);
		startActivity(i);
	}

	protected boolean clientValidate() {
		int accountLength = account.getText().length();
		int passwordLength = password.getText().length();
		if (accountLength == 0) {
			account.requestFocus();
			account.setError(getString(R.string.notnull));
			return false;
		} else {
			account.setError(null);
		}
		if (passwordLength == 0) {
			password.requestFocus();
			password.setError(getString(R.string.notnull));
			return false;
		} else {
			password.setError(null);
		}
		if (accountLength > 16) {
			account.requestFocus();
			account.setError(getString(R.string.accounttoolong));
			return false;
		} else {
			account.setError(null);
		}
		if (passwordLength > 32) {
			password.requestFocus();
			password.setError(getString(R.string.passwordtoolong));
			return false;
		} else {
			password.setError(null);
		}
		return true;
	}
}
